package com.heima.wemedia.interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.thread.WmUserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求头
        //通过请求头获取userId
        String userId = request.getHeader("userId");

        //判空 如果空 阻止
        if (StringUtils.isEmpty(userId)){
            log.info("用户没有登录");
            return false;
        }
        //不为空 存放到ThreadLocal
        //创建ThreadLocal类 get set
        //调用ThreadLocal类的set方法 往里面存储数据
        WmUser wmUser = new WmUser();
        wmUser.setId(Integer.parseInt(userId));
        WmUserThreadLocal.set(wmUser);


        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清楚ThreadLocal
        WmUserThreadLocal.remove();

    }
}
